package cn.edu.cqut.mdm.core.dispatcher;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import cn.edu.cqut.mdm.container.LocalDefinedModuleContainer;
import cn.edu.cqut.mdm.core.message.RequestMessage;
import cn.edu.cqut.mdm.core.message.ResponseMessage;
import cn.edu.cqut.mdm.core.module.ModuleEntity;

public class LocalDispatcher implements Dispatcher {
	private static LocalDispatcher localDispatcher = new LocalDispatcher();
	private LocalDispatcher() {
	}
	public static LocalDispatcher getLocalDispatcher() {
		return localDispatcher;
	}
	
	@Override
	public ResponseMessage dispatch(RequestMessage requestMessage) {
		ModuleEntity moduleEntity = LocalDefinedModuleContainer.getInstance().getModule(requestMessage.getRemoteModuleUid());
		ResponseMessage responseMessage = new ResponseMessage();
		try {
			Method remoteMethod = moduleEntity.getModuleClazz().getDeclaredMethod(requestMessage.getMethod().getName(), requestMessage.getMethod().getParameterTypes());
			Object result = remoteMethod.invoke(moduleEntity.getModuleClazz().newInstance(), requestMessage.getParameters().toArray());
			responseMessage.setReturnValue(result);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return responseMessage;
	}
}
